package fr.efrei.tradesys.treatments;

import java.util.Random;

import fr.efrei.tradesys.hibernate.beans.AppUser;
import fr.efrei.tradesys.hibernate.factory.DaoFactory;

public class Generators
{

	public String generateLogin(AppUser u)
	{
		String lastname = u.getLastname().toLowerCase();
		String firstname = u.getFirstname().toLowerCase();
		String login = lastname.substring(0, Math.min(8, lastname.length()));
		int i = 0;
		int j = 0;
		String tmpLogin = login + firstname.substring(0, 1);
		// We check that the login did not already exist
		while (DaoFactory.getInstance().getAppUserDao().getAppUser(tmpLogin) != null)
		{
			++i;
			if (i < firstname.length())
				tmpLogin = login + firstname.substring(i, i + 1);
			else
				tmpLogin = login + j++;
		}
		return tmpLogin;
	}

	public String generatePassword()
	{
		String charset = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
				+ "abcdefghijklmnopqrstuvwxyz";
		Random rand = new Random(System.currentTimeMillis());
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 8; i++)
		{
			int pos = rand.nextInt(charset.length());
			sb.append(charset.charAt(pos));
		}
		return sb.toString();
	}

}
